<?php
namespace App\Services;

use App\Models\CouponsConfig;
use App\Models\Goods;
use App\Models\IntegralRule;
use App\Models\User;
class GoodsShopService{

    /**
     * @param User $user 兑换人
     * @param int $goods_id 兑换的产品id
     */
    //积分兑换流程
    public function goodsShop(User $user,int $goods_id){
        //查找卡券的过期天数
        $pass_day = IntegralRule::getPassDay();
        $goods = Goods::find($goods_id);
        //增加卡券使用记录(里边包含了去除积分)
        $user->userIntegralLogs()->create([
            "integral"=>-$goods->integral,
            "des"    =>"兑换".$goods->short_name,
            "is_checked"=>true,
        ]);
        $price = $goods->price?$goods->price:0;
        //新增用户卡券 、卡券发放完毕  (卡券发放通知在模型事件的监听器里边)
        $user->coupons()->create([
            "end_date"=>now()->addDays($pass_day)->toDateString(),
            "title"   =>$goods->short_name."券",
            "descript"=>$goods->coupon_des?$goods->coupon_des:"持此券到店可享".$price."元购买".$goods->short_name."一件",
            "goods_id"=>$goods->id,
            "type"=>CouponsConfig::COUPONS_TYPE_SHOP
        ]);
    }
}
